package api

import (
	"net/http"
	"pids-cloud-server/app/common"
	"pids-cloud-server/entity"
	"pids-cloud-server/utils"
	"time"

	"github.com/gin-gonic/gin"
)

// UpdateAlarmThreshold
// @Summary 更新告警阈值
// @Description 更新告警阈值
// @Tags 告警阈值
// @Accept json
// @Produce json
// @Param alarmThreshold body []entity.AlarmThreshold true "告警阈值"
// @Success 200 {object} common.Result
// @Failure 400 {object} common.Result
// @Router /alarmThreshold/updateThreshold [post]
func UpdateAlarmThreshold(c *gin.Context) {
	var alarmThresholdInputList []entity.AlarmThreshold
	db := utils.GetDB()
	if db == nil {
		common.ErrorResponse(c, http.StatusInternalServerError, "数据库连接失败")
		return
	}
	if err := c.BindJSON(&alarmThresholdInputList); err != nil {
		common.ErrorResponse(c, http.StatusBadRequest, err.Error())
		return
	}

	// 使用事务包装整个操作
	tx := db.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	// 提取所有host_ip
	var hostIps []string
	for _, alarmThreshold := range alarmThresholdInputList {
		hostIps = append(hostIps, alarmThreshold.HostIP)
	}

	// 查询已存在的记录
	var alarmThresholdList []entity.AlarmThreshold
	savedThresholdMap := make(map[string]entity.AlarmThreshold)
	if err := tx.Where("host_ip IN (?)", hostIps).Find(&alarmThresholdList).Error; err != nil {
		tx.Rollback()
		common.ErrorResponse(c, http.StatusInternalServerError, "查询已存在记录失败: "+err.Error())
		return
	}

	for _, alarmThreshold := range alarmThresholdList {
		savedThresholdMap[alarmThreshold.HostIP] = alarmThreshold
	}

	// 分离新增和更新的记录
	var newRecords []entity.AlarmThreshold
	var updateRecords []entity.AlarmThreshold
	currentTime := time.Now()

	for _, newAlarmThreshold := range alarmThresholdInputList {
		if existingThreshold, exists := savedThresholdMap[newAlarmThreshold.HostIP]; !exists {
			// 新增记录
			newAlarmThreshold.ID = utils.GenerateID().Int64()
			newAlarmThreshold.CreateTime = currentTime
			newAlarmThreshold.ModifyTime = currentTime
			newRecords = append(newRecords, newAlarmThreshold)
		} else {
			// 更新记录
			newAlarmThreshold.ID = existingThreshold.ID
			newAlarmThreshold.CreateTime = existingThreshold.CreateTime // 保持原创建时间
			newAlarmThreshold.ModifyTime = currentTime
			updateRecords = append(updateRecords, newAlarmThreshold)
		}
	}

	// 批量插入新记录
	if len(newRecords) > 0 {
		// 使用批量插入，每批50条
		batchSize := 50
		if err := tx.CreateInBatches(newRecords, batchSize).Error; err != nil {
			tx.Rollback()
			common.ErrorResponse(c, http.StatusInternalServerError, "批量插入失败: "+err.Error())
			return
		}
	}

	// 批量更新已存在的记录
	if len(updateRecords) > 0 {
		// 使用批量更新，每批50条
		batchSize := 50
		for i := 0; i < len(updateRecords); i += batchSize {
			end := i + batchSize
			if end > len(updateRecords) {
				end = len(updateRecords)
			}

			batch := updateRecords[i:end]
			for _, record := range batch {
				// 使用 Select("*") 确保所有字段都被更新，包括0值
				if err := tx.Model(&record).Select("*").Where("id = ?", record.ID).Updates(map[string]interface{}{
					"host_ip":           record.HostIP,
					"cpu_min":           record.CPUMin,
					"cpu_max":           record.CPUMax,
					"memory_min":        record.MemoryMin,
					"memory_max":        record.MemoryMax,
					"disk_min":          record.DiskMin,
					"disk_max":          record.DiskMax,
					"disk_max_enable":   record.DiskMaxEnable,
					"disk_nor_enable":   record.DiskNorEnable,
					"disk_min_enable":   record.DiskMinEnable,
					"memory_max_enable": record.MemoryMaxEnable,
					"memory_nor_enable": record.MemoryNorEnable,
					"memory_min_enable": record.MemoryMinEnable,
					"cpu_max_enable":    record.CPUMaxEnable,
					"cpu_nor_enable":    record.CPUNorEnable,
					"cpu_min_enable":    record.CPUMinEnable,
					"cpu_nor":           record.CPUNor,
					"memory_nor":        record.MemoryNor,
					"disk_nor":          record.DiskNor,
					"creator_id":        record.CreatorID,
					"creator":           record.Creator,
					"modify_id":         record.ModifyID,
					"modifier":          record.Modifier,
					"modify_time":       record.ModifyTime,
				}).Error; err != nil {
					tx.Rollback()
					common.ErrorResponse(c, http.StatusInternalServerError, "批量更新失败: "+err.Error())
					return
				}
			}
		}
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		common.ErrorResponse(c, http.StatusInternalServerError, "事务提交失败: "+err.Error())
		return
	}

	common.SuccessResponse(c, gin.H{
		"created": len(newRecords),
		"updated": len(updateRecords),
	})
}
